package com.cfets.annualAssessment.controller;

import com.alibaba.fastjson.JSON;
import com.cfets.annualAssessment.base.UserSessionHolder;
import com.cfets.annualAssessment.entity.CommPara;
import com.cfets.annualAssessment.entity.MyWxJsapiSignature;
import com.cfets.annualAssessment.entity.UserSession;
import com.cfets.annualAssessment.service.AnnualParaService;
import com.cfets.annualAssessment.util.*;
import com.cfets.annualAssessment.weixinService.MyWxMpServiceImpl;
import lombok.extern.log4j.Log4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * Created by ShenYiChou on 2017/2/15.
 */
@Log4j
@Controller
@RequestMapping("/admin/wx")
public class WeixinController {

    @Autowired
    private MyWxMpServiceImpl mpService;
    @Autowired
    protected WxMpConfigStorage wxMpConfigStorage;
    @Autowired
    private RedisRunner redisRunner;
    @Autowired
    private AnnualParaService annualParaService;

    @RequestMapping("/theme")
    public void WechatOauthInterceptor(Model model, HttpServletRequest request,HttpServletResponse response) throws Exception {
        if(request.getRequestURL().indexOf("websocket")>=1){
            return;
        }
        UserSession userSession = new UserSession();
        if (!CheckUtil.isEmpty(request.getParameter("state"))) {
            String uri;
            if(request.getParameter("state").equals("-1")){
                uri = "http://online1.chinamoney.com.cn/view/index.html";
            }else{
                return;
            }

            String code = request.getParameter("code");
            log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"+code);
            if (CheckUtil.isEmpty(code)) {
                throw new RuntimeException("Wechat Oauth Failed!");
            } else {
                WxMpOAuth2AccessToken wxMpOAuth2AccessToken = mpService.oauth2getAccessToken(code);
                WxMpUser wxMpUser = mpService.oauth2getUserInfo(wxMpOAuth2AccessToken,"zh_CN");
                log.info("*****oauth2 get UserInfo : " + JSON.toJSONString(wxMpUser));
                if(!CheckUtil.isEmpty(wxMpUser)) {
                    userSession.setOpenId(wxMpUser.getOpenId());
//					FollowedUser user = transWxUserToFollowedUser(wxMpUser);
                    String cookieValue = CookieUtil.getCookie(request, Constant.COOKIE_KEY);
                    if (CheckUtil.isEmpty(cookieValue)) {
                        cookieValue = UUID.randomUUID().toString();
                    }
                    //把获取到到值放到userSession里面
//					userSession.setUserId(user.getId());
                    userSession.setWeChatName(wxMpUser.getNickname());
                    userSession.setOpenId(wxMpUser.getOpenId());
                    CookieUtil.addCookie(response, Constant.OAUTH_OPENID_COOKIE_KEY, wxMpUser.getOpenId());
//					CookieUtil.addCookie(response, Constant.USER_ID_COOKIE_KEY, user.getId().toString());
                    CookieUtil.addCookie(response, Constant.COOKIE_KEY, cookieValue);
//                    String uri = request.getHeader("X-request-uri");
//                    String uri = "http://online1.chinamoney.com.cn/view/index.html";              //上线运行
//                    if(uri==null||"".equals(uri)){
//                        uri=request.getRequestURL().toString();
//                    }
                    log.info("X-request-uri : "+uri);
                    // 然后存到redis
                    userSession.setK(cookieValue);
                    String userAgent = request.getHeader("User-Agent");
                    userSession.setUserAgent(userAgent);
                    redisRunner.cacheAddUpdate(Constant.REDIS_DB_USER_SESSION, cookieValue, userSession, Constant.REDIS_USER_SESSION_EXPIRY);
                    response.sendRedirect(uri);
                    return;
                }
            }
        }
        return;
    }
    @RequestMapping("/user")
    public ResponseEntity<?> UserSessionInterceptor(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if(request.getRequestURL().indexOf("websocket")>=1){
            return new ResponseEntity<>(true, HttpStatus.OK);
        }
        String cookieValue = CookieUtil.getCookie(request, Constant.COOKIE_KEY);
        CommPara commPara = new CommPara();
//        //是否年检 start
//        if (this.annualParaService.isDuringAnnual().isEmpty()){
//            commPara.setCommInt(0);
//        }else{
//            commPara.setCommInt(1);
//        }
//        //是否年检 end
        if (CheckUtil.isEmpty(cookieValue)) {
            cookieValue = UUID.randomUUID().toString();
        }
        String openId = null;
        String oauthOpenId = CookieUtil.getCookie(request, Constant.OAUTH_OPENID_COOKIE_KEY);
        UserSession userSession = null;
        if (!CheckUtil.isEmpty(cookieValue)) {
            userSession = redisRunner.cacheGet(Constant.REDIS_DB_USER_SESSION, cookieValue, UserSession.class);
            log.info("****UserSessionInterceptor get redis usersession : " + JSON.toJSONString(userSession));
        }
//        //开发打开 start
//        if(userSession == null){
//            userSession = UserSessionHolder.get();
//        }
//        //开发打开 end
        if (userSession != null) {
            openId = userSession.getOpenId();
        }
        if (userSession == null && oauthOpenId == null && openId == null) {
            //如果没有取到openID,说明是没有通过权限链接进入,需要重定向到权限链接里面去,要从getHeader里面去uri
            log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ oauthOpenId is null ");
            CookieUtil.removeCookie(response, Constant.COOKIE_KEY);
////			String path =madeUrl(request);
////            String uri = request.getHeader("X-request-url");
//
//            String uri = "http://online1.chinamoney.com.cn/access/admin/wx/theme";           //上线运行
//
////            if(uri==null||"".equals(uri)){
////                uri=request.getRequestURL().toString();
////            }else {
////                uri=uri.replace("?"+request.getQueryString(),"");
////            }
//            log.info("X-request-url : "+uri);
//            String path = madeUrl(uri,request);
//            log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + path);
//            String url = mpService.oauth2buildAuthorizationUrl(path,"snsapi_userinfo","-1");
//            log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ url" + url);
//            response.sendRedirect(url);
            return new ResponseEntity<>(true, HttpStatus.OK);
//            return new ResponseEntity<>(commPara, HttpStatus.OK);
        }
//        userSession.setK(cookieValue);
//        redisRunner.cacheAddUpdate(Constant.REDIS_DB_USER_SESSION, cookieValue, userSession, Constant.REDIS_USER_SESSION_EXPIRY);
//        UserSessionHolder.put(userSession);

        if (userSession != null) {
            commPara.setCommString(userSession.getWeChatName());
        }
        return new ResponseEntity<>(commPara, HttpStatus.OK);

    }

    @RequestMapping("/ticket")
    public ResponseEntity<?> ticketInterceptor(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if(request.getRequestURL().indexOf("websocket")>=1){
            return new ResponseEntity<>(true, HttpStatus.OK);
        }
        String url = request.getHeader("referer");
//        String url = "http://online1.chinamoney.com.cn/game/success.html";
        MyWxJsapiSignature myWxJsapiSignature = new MyWxJsapiSignature();
        WxJsapiSignature wxJsapiSignature = mpService.createJsapiSignature(url);
        myWxJsapiSignature.setUrl(wxJsapiSignature.getUrl());
        myWxJsapiSignature.setAppid(wxJsapiSignature.getAppid());
        myWxJsapiSignature.setNoncestr(wxJsapiSignature.getNoncestr());
        myWxJsapiSignature.setSignature(wxJsapiSignature.getSignature());
        myWxJsapiSignature.setTimestamp(wxJsapiSignature.getTimestamp());

        return new ResponseEntity<>(myWxJsapiSignature, HttpStatus.OK);
    }

    private static String madeUrl(String uri,HttpServletRequest request) {
        String paras = request.getQueryString();
        if(paras!=null)
            return uri+"?"+paras;
        else return uri;
    }
}
